package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitService rabbitService;

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		//	创建map 集合
		Map<String, Object> map = new HashMap<>();
		//	数据存储在MongoDB；
		//	获取集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//	设置查询条件;
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC, "updateTime")).limit(1);
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//	判断
		if (null != userListenProcess){
			map.put("albumId",userListenProcess.getAlbumId());
			map.put("trackId",userListenProcess.getTrackId());
		}
		//	返回数据
		return map;
	}

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//	先查询MongoDB中是否有该声音的播放记录;
		//	组成集合名称：
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//	从集合中获取对应的播放时长; userId and trackId;
		Query query = Query.query(Criteria.where("trackId").is(userListenProcessVo.getTrackId()));
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//	判断
		if (null != userListenProcess){
			//	覆盖写声音播放进度;
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setUpdateTime(new Date());
		} else {
			//	新增播放进度;
			userListenProcess = new UserListenProcess();
			//	赋值：
			userListenProcess.setUserId(userId);
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
		}
		//	保存数据;
		this.mongoTemplate.save(userListenProcess, collectionName);
		//	利用分布式锁思想解决声音重复播放问题，会造成恶意刷单; setnx + setex = set key value ex nx timeout;
		//	key=userId:trackId; value="1"; 24 H;
		String key = userId + ":" + userListenProcess.getTrackId();
		Boolean result = this.redisTemplate.opsForValue().setIfAbsent(key, "1", 24, TimeUnit.HOURS);
		//	判断当前结果result;
		if (result){
			//	说明当前这个用户是第一次播放，专辑+声音；播放量+1;
			TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
			trackStatMqVo.setCount(1);
			trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			trackStatMqVo.setTrackId(userListenProcess.getTrackId());
			trackStatMqVo.setAlbumId(userListenProcess.getAlbumId());
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			trackStatMqVo.setBusinessNo(uuid);
			rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(trackStatMqVo));
		}
	}

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//	组成集合名称：
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//	从集合中获取对应的播放时长; userId and trackId;
		Query query = Query.query(Criteria.where("trackId").is(trackId));
		UserListenProcess userListenProcess = mongoTemplate.findOne(query, UserListenProcess.class, collectionName);
		//	判断
		if (null != userListenProcess){
			return userListenProcess.getBreakSecond();
		}
		return new BigDecimal("0.00");
	}
}
